google.load("visualization", "1", {
	packages : [ "corechart" ]
});
google.setOnLoadCallback(init);

var pollutionData = null;
function drawChart() {
	if (!pollutionData)
		return;

	var substance = $("#select-substance").val();

	var table_data = [ [ 'Time', substance.toUpperCase() + ' Level' ] ];
	for (var i = 0; i < pollutionData.length; i++) {
		var d = new Date(Date
				.parse(pollutionData[pollutionData.length - i - 1].time_stamp));
		// table_data.push([ d,
		// pollutionData[pollutionData.length - i - 1][substance] ]);
		table_data
				.push([
						d,
						getPollutionLevel(pollutionData[i][substance],
								substance) + 1 ]);

	}
	//
	// [
	// [ 'Time', substance + ' Level' ], [ '6.00 AM', 10 ],
	// [ '12:00 PM', 1, ], [ '06:00 PM', 6 ], [ '00:00 AM', 5 ] ]

	var data = google.visualization.arrayToDataTable(table_data);

	var options = {
		title : 'Last 24 Hour\'s ' + substance.toUpperCase() + ' level',
		vAxis : {
			title : substance.toUpperCase() + ' level',
			gridlines : {
				count : 5
			},
			ticks : [ 3, 6, 9, 10 ],
			minValue : 0
		},
		hAxis : {
			format : 'MMM d, y HH:MM',
			gridlines : {
				count : 6
			}
		}
	};

	var chart = new google.visualization.AreaChart(document
			.getElementById('chart_div'));
	chart.draw(data, options);
}

function init() {
	loadCurrentData();
	loadGraph($("#select-time-range").val());
	$("#select-time-range").change(function() {
		loadGraph($("#select-time-range").val());
	});

	$("#select-substance").change(function() {
		loadGraphForSubstance($("#select-substance").val());
	});

}

function updatePollutionData(json) {
	// co
	// no2
	// o3
	// pm10
	// pm2p5
	// so2
	// time_stamp
	// latitude
	// longitude
	var co = Math.round(json.co * 100) / 100;// making it two decimal places
	$("#co").html(co + "<sub>&mu;g/m<sup>3</sup></sub>");

	var no2 = Math.round(json.no2 * 100) / 100;// making it two decimal places
	$("#no2").html(no2 + "<sub>&mu;g/m<sup>3</sup></sub>");
	$("#no2").parent().addClass(getClass(no2, "no2"));

	var pm10 = Math.round(json.pm10 * 100) / 100;// making it two decimal
	// places
	$("#pm10").html(pm10 + "<sub>&mu;g/m<sup>3</sup></sub>");
	$("#pm10").parent().addClass(getClass(pm10, "pm10"));

	var so2 = Math.round(json.so2 * 100) / 100;// making it two decimal places
	$("#so2").html(so2 + "<sub>&mu;g/m<sup>3</sup></sub>");
	$("#so2").parent().addClass(getClass(so2, "so2"));

	var o3 = Math.round(json.o3 * 100) / 100;// making it two decimal places
	$("#o3").html(o3 + "<sub>&mu;g/m<sup>3</sup></sub>");
	$("#o3").parent().addClass(getClass(o3, "o3"));

	var pm2p5 = Math.round(json.pm2p5 * 100) / 100;// making it two decimal
	// places
	$("#pm2p5").html(pm2p5 + "<sub>&mu;g/m<sup>3</sup></sub>");
	$("#pm2p5").parent().addClass(getClass(pm2p5, "pm2p5"));
}

function loadCurrentData() {
	$.ajax({
		type : "GET",
		url : "observation?current=true",
		dataType : "json"
	}).done(function(json) {
		updatePollutionData(json);
	});

}

function loadGraphForSubstance() {
	drawChart();
}

function loadGraph(days) {
	$.ajax({
		type : "GET",
		url : "observation?days=" + days,
		dataType : "json"
	}).done(function(json) {
		pollutionData = json;
		drawChart(json);
	});
}

function weather() {
	// http://api.wunderground.com/api/3b4c284cf1faa2dd/conditions/q/55.9520600,-3.1964800.json
	var weatherData = {
		"response" : {
			"version" : "0.1",
			"termsofService" : "http://www.wunderground.com/weather/api/d/terms.html",
			"features" : {
				"conditions" : 1
			}
		},
		"current_observation" : {
			"image" : {
				"url" : "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
				"title" : "Weather Underground",
				"link" : "http://www.wunderground.com"
			},
			"display_location" : {
				"full" : "Edinburgh, United Kingdom",
				"city" : "Edinburgh",
				"state" : "",
				"state_name" : "United Kingdom",
				"country" : "UK",
				"country_iso3166" : "GB",
				"zip" : "00000",
				"magic" : "166",
				"wmo" : "03160",
				"latitude" : "55.950000",
				"longitude" : "-3.190000",
				"elevation" : "36.00000000"
			},
			"observation_location" : {
				"full" : "Leith, Edinburgh, CITY OF EDINBURGH",
				"city" : "Leith, Edinburgh",
				"state" : "CITY OF EDINBURGH",
				"country" : "UNITED KINGDOM",
				"country_iso3166" : "GB",
				"latitude" : "55.976017",
				"longitude" : "-3.182199",
				"elevation" : "90 ft"
			},
			"estimated" : {},
			"station_id" : "IMIDLOTH12",
			"observation_time" : "Last Updated on June 27, 2:45 PM BST",
			"observation_time_rfc822" : "Fri, 27 Jun 2014 14:45:12 +0100",
			"observation_epoch" : "1403876712",
			"local_time_rfc822" : "Fri, 27 Jun 2014 14:46:13 +0100",
			"local_epoch" : "1403876773",
			"local_tz_short" : "BST",
			"local_tz_long" : "Europe/London",
			"local_tz_offset" : "+0100",
			"weather" : "Mostly Cloudy",
			"temperature_string" : "55.6 F (13.1 C)",
			"temp_f" : 55.6,
			"temp_c" : 13.1,
			"relative_humidity" : "70%",
			"wind_string" : "Calm",
			"wind_dir" : "North",
			"wind_degrees" : 0,
			"wind_mph" : 0.0,
			"wind_gust_mph" : 0,
			"wind_kph" : 0,
			"wind_gust_kph" : 0,
			"pressure_mb" : "1015",
			"pressure_in" : "29.98",
			"pressure_trend" : "0",
			"dewpoint_string" : "46 F (8 C)",
			"dewpoint_f" : 46,
			"dewpoint_c" : 8,
			"heat_index_string" : "NA",
			"heat_index_f" : "NA",
			"heat_index_c" : "NA",
			"windchill_string" : "NA",
			"windchill_f" : "NA",
			"windchill_c" : "NA",
			"feelslike_string" : "55.6 F (13.1 C)",
			"feelslike_f" : "55.6",
			"feelslike_c" : "13.1",
			"visibility_mi" : "6.2",
			"visibility_km" : "10.0",
			"solarradiation" : "283",
			"UV" : "6",
			"precip_1hr_string" : "0.00 in ( 0 mm)",
			"precip_1hr_in" : "0.00",
			"precip_1hr_metric" : " 0",
			"precip_today_string" : "0.00 in (0 mm)",
			"precip_today_in" : "0.00",
			"precip_today_metric" : "0",
			"icon" : "mostlycloudy",
			"icon_url" : "http://icons.wxug.com/i/c/k/mostlycloudy.gif",
			"forecast_url" : "http://www.wunderground.com/global/stations/03160.html",
			"history_url" : "http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IMIDLOTH12",
			"ob_url" : "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=55.976017,-3.182199",
			"nowcast" : ""
		}
	};

}

function getPollutionLevel(value, substance) {
	var boundaries = [];
	switch (substance) {
	case "o3":
		boundaries = [ 0, 34, 67, 101, 121, 141, 161, 188, 214, 241 ];
		break;
	case "no2":
		boundaries = [ 0, 68, 135, 201, 268, 335, 401, 468, 535, 601 ];
		break;
	case "so2":
		boundaries = [ 0, 89, 178, 267, 355, 444, 533, 711, 888, 1065 ];
		break;
	case "pm2p5":
		boundaries = [ 0, 12, 24, 36 - 41, 42, 48, 54, 59, 65, 71 ];
		break;
	case "pm10":
		boundaries = [ 0, 17, 34, 51, 59, 67, 76, 84, 92, 101 ];
		break;
	default:
		return -1;
	}
	var i = 0;
	for (; i < boundaries.length; i++) {
		if (value < boundaries[i]) {
			break;
		}
	}
	return i - 1;
}
function getClass(value, substance) {
	var classNames = [ "low-1", "low-2", "low-3", "moderate-1", "moderate-2",
			"moderate-3", "high-1", "high-2", "high-3", "very-high" ];
	var level = getPollutionLevel(value, substance);
	if (level == -1)
		return "na";
	return classNames[level];
}

function getTime(d) {
	var AM = true;
	var hours = d.getHours();
	if (hours >= 12) {
		AM = false;
		hours = hours - 12;
	}

	if (hours < 10) {
		hours = "0" + hours;
	}

	var minutes = d.getMinutes();
	if (minutes < 10) {
		minutes = "0" + minutes;
	}
	return hours + ":" + minutes + AM ? " AM" : " PM";
}